package test4_16.demo01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServerTest {
    public static void main(String[] args) {

        try {
            //创建端口
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("创建服务器端口");

            //分配，等待连接，accept阻塞方法 没有连接一直等待
            Socket socket = serverSocket.accept();
            System.out.println("服务器与客户端连接成功");

            //获取客户端数据
            InputStream is = socket.getInputStream();
            //转成字符输出流
            InputStreamReader isr = new InputStreamReader(is);
            //缓冲流
            BufferedReader br = new BufferedReader(isr);

            System.out.println("服务器端接受数据");

            //读取数据并输出
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("客户端说：" + line);
                if (line.equals("拜拜")) {
                    break;
                }
            }

            System.out.println("断开连接");
            br.close();
            socket.close();
            serverSocket.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
